package cn.lblbc.downloadlibdemo

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import cn.lblbc.downloadlib.*

class MainActivity : AppCompatActivity() {
    
    private lateinit var downloadManager: DownloadManager
    private lateinit var taskAdapter: DownloadTaskAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var fab: FloatingActionButton
    
    companion object {
        private const val TAG = "MainActivity"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        Log.d(TAG, "onCreate: Initializing download manager")
        // 初始化下载管理器
        val config = DownloadConfig.Builder()
            .setConcurrentTaskNum(3)
            .setMaxChunksPerFile(4)
            .setChunkSize(2 * 1024 * 1024) // 2MB
            .build()
        DownloadManager.init(this, config)
        downloadManager = DownloadManager.getInstance()
        
        // 初始化UI
        initUI()
        
        // 观察数据变化
        observeDownloadTasks()
    }
    
    private fun initUI() {
        Log.d(TAG, "initUI: Initializing UI components")
        // 设置RecyclerView
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        taskAdapter = DownloadTaskAdapter(mutableListOf()) { task, action ->
            when (action) {
                "pause" -> {
                    Log.d(TAG, "initUI: Pause action clicked for task ${task.taskId}")
                    downloadManager.pauseDownload(task.taskId)
                    Log.d(TAG, "initUI: Pause command sent for task ${task.taskId}")
                }
                "resume" -> {
                    Log.d(TAG, "initUI: Resume action clicked for task ${task.taskId}")
                    downloadManager.resumeDownload(task.taskId)
                    Log.d(TAG, "initUI: Resume command sent for task ${task.taskId}")
                }
                "delete" -> {
                    Log.d(TAG, "initUI: Delete action clicked for task ${task.taskId}")
                    deleteTask(task.taskId)
                }
            }
        }
        recyclerView.adapter = taskAdapter
        
        // 设置悬浮按钮
        fab = findViewById(R.id.fab)
        fab.setOnClickListener {
            Log.d(TAG, "Floating action button clicked")
            addNewTask()
        }
    }
    
    private fun observeDownloadTasks() {
        Log.d(TAG, "observeDownloadTasks: Starting to observe download tasks")
        val liveData = downloadManager.observeAllDownloadRecords()
        liveData.observe(this, Observer { records ->
            Log.d(TAG, "observeDownloadTasks: Received ${records?.size ?: 0} records from LiveData")
            if (records != null) {
                taskAdapter.updateTasks(records)
                Log.d(TAG, "observeDownloadTasks: Updated adapter with ${records.size} records")
            }
        })
    }
    
    private fun addNewTask() {
        Log.d(TAG, "addNewTask: Creating new task")
        val packageName = "xxx.yyy"
        val fileUrl = "https://ms-gdown.baidu.com/appcenter/pkg/upload/0d92fb07d6927b4c891ff3dd4f2b619b?md5hash=ad9cb6222ef7270e95fba8d6b08ea4bc&timestamp=1761310334"
        val fileType = "apk"
        
        val fileInfo = DownloadFileInfo().apply {
            this.fileUrl = fileUrl
            this.fileName = "sample.apk"
            this.fileType = fileType
            this.fileSize = 1024 * 1024 // 示例大小 1MB
            this.createTime = System.currentTimeMillis()
            this.updateTime = System.currentTimeMillis()
            this.status = DownloadConstants.STATUS_PENDING
        }
        
        val task = DownloadTaskBuilder(packageName)
            .setFiles(listOf(fileInfo))
            .build()
            
        Log.d(TAG, "addNewTask: Submitting task with package: $packageName")
        downloadManager.submitTaskAsync(task, object : DownloadManager.SubmitTaskCallback {
            override fun onResult(result: TaskOperateResult) {
                Log.d(TAG, "addNewTask: Task submission result - success: ${result.isSuccess}, message: ${result.message}")
                if (result.isSuccess) {
                    Log.d(TAG, "addNewTask: Task submitted successfully")
                } else {
                    Log.e(TAG, "addNewTask: Failed to submit task: ${result.message}")
                }
            }
        })
    }
    
    private fun deleteTask(taskId: Long) {
        Log.d(TAG, "deleteTask: Deleting task with ID: $taskId")
        downloadManager.deleteDownloadAsync(taskId, true, object : DownloadManager.DeleteTaskCallback {
            override fun onResult(success: Boolean) {
                Log.d(TAG, "deleteTask: Delete task result - success: $success")
                if (success) {
                    Log.d(TAG, "deleteTask: Task deleted successfully")
                } else {
                    Log.e(TAG, "deleteTask: Failed to delete task")
                }
            }
        })
    }
}